// src/api/api.js
import axios from "axios";
import config from "@/config";

// 创建一个 Axios 实例
const apiClient = axios.create({
  baseURL: config.baseURL,  // 使用统一的配置
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

// 创建一个封装的API请求方法
export const fetchActivities = (endpoint) => {
  return apiClient
    .get(endpoint)
    .then((response) => {
      // 假设后端返回的数据结构中已经包含了点赞信息
      // 如果需要某些适配处理，可以在这里进行
      return response.data;
    })
    .catch((error) => {
      console.error("获取活动列表失败:", error);
      throw error;
    });
};

/**
 * 获取单个活动的详细信息（包含点赞信息）
 */
export const fetchActivityDetail = (id) => {
  console.log("调用fetchActivityDetail API，活动ID:", id);

  // 检查id是否为有效值
  if (!id) {
    console.error("活动ID无效:", id);
    return Promise.reject(new Error("活动ID无效"));
  }

  return apiClient
    .get(`/activities/${id}/detail`)
    .then((response) => {
      console.log("活动详情API响应数据:", response.data);

      // 确保活动对象有点赞相关字段
      const activity = response.data;

      // 如果返回数据不包含点赞字段，记录警告
      if (
        activity &&
        activity.isLiked === undefined &&
        activity.liked === undefined
      ) {
        console.warn("活动详情返回数据中没有点赞状态字段");
      }

      // 如果返回数据不包含点赞数量字段，记录警告
      if (
        activity &&
        activity.likeCount === undefined &&
        activity.count === undefined &&
        activity.likedCount === undefined &&
        activity.likesCount === undefined
      ) {
        console.warn("活动详情返回数据中没有点赞数量字段");
      }

      return activity;
    })
    .catch((error) => {
      console.error(`获取活动详情失败:`, error);
      if (error.response) {
        console.error("错误响应:", error.response.status, error.response.data);

        // 如果是404错误，尝试使用备用路径
        if (error.response.status === 404) {
          console.log("尝试备用路径获取活动详情");
          return apiClient
            .get(`/activities/${id}`)
            .then((response) => {
              console.log("备用路径活动详情响应:", response.data);
              return response.data;
            })
            .catch((fallbackError) => {
              console.error("备用路径获取活动详情失败:", fallbackError);
              throw fallbackError;
            });
        }
      }
      throw error;
    });
};

/**
 * 根据 ID 获取活动详情
 * @param {number|string} id - 活动的 ID
 * @returns {Promise<Object>} - 返回活动详情
 */
export const fetchActivityById = (id) => {
  if (!id) {
    console.log("ID is required to fetch activity details.");
    return "";
  }

  return axios
    .get(`${config.baseURL}/activities/${id}`)
    .then((response) => response.data)
    .catch((error) => {
      console.error("There was an error fetching the activity details!", error);
      throw error;
    });
};

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token"); // 从 localStorage 获取 token
    // const token = sessionStorage.getItem('token'); // 从 sessionStorage 获取 token

    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // 处理响应错误，例如 token 过期等
    if (error.response.status === 401) {
      // 清除 token 并重定向到登录页面
      localStorage.removeItem("token");
      // sessionStorage.removeItem('token');
      window.location.href = "/login";
    }

    return Promise.reject(error);
  }
);

export async function verifyToken(token) {
  try {
    const response = await apiClient.get("/verify-token", {
      headers: { Authorization: `Bearer ${token}` },
      skipAuth: true, // Add this flag to skip the auth interceptor
    });
    console.log("token verify response", response);
    console.log(response);
    return response.status === 200;
  } catch (error) {
    return false;
  }
}

export const fetchGetRequest = (endpoint) => {
  console.log(`${config.baseURL}${endpoint}`);
  return axios
    .get(`${config.baseURL}${endpoint}`)
    .then((response) => response.data)
    .catch((error) => {
      console.error("There was an error with the GET request!", error);
      throw error;
    });
};

export const fetchPostRequest = (endpoint, data) => {
  return axios
    .post(`${config.baseURL}${endpoint}`, data)
    .then((response) => response.data)
    .catch((error) => {
      console.error("There was an error with the POST request!", error);
      throw error;
    });
};

export const fetchJobById = (id) => {
  return axios
    .get(`${config.baseURL}/jobs/${id}`)
    .then((response) => response.data)
    .catch((error) => {
      console.error("There was an error fetching the job details!", error);
      throw error;
    });
};

export const fetchConversations = () => {
  return apiClient
    .get("/chat/conversations") // 不需要 config.baseURL，因为 apiClient 已经配置了
    .then((response) => response.data)
    .catch((error) => {
      console.error("There was an error fetching the conversations!", error);
      throw error;
    });
};

export const fetchMessagesByConversationId = (conversationId) => {
  return axios
    .post(`${config.baseURL}/chat/messages/list`, {
      conversationId: conversationId.toString(),
    })
    .then((response) => response.data)
    .catch((error) => {
      console.error("There was an error fetching the messages!", error);
      throw error;
    });
};

export const sendMessage = (conversationId, message) => {
  return apiClient
    .post("/chat/messages", {
      conversationId: conversationId,
      message: message,
    })
    .then((response) => response.data)
    .catch((error) => {
      console.error("There was an error sending the message!", error);
      throw error;
    });
};

export const postFormDataRequest = (endpoint, data) => {
  return apiClient
    .post(`${endpoint}`, data, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    })
    .then((response) => response.data)
    .catch((error) => {
      console.error("There was an error with the POST request!", error);
      throw error;
    });
};

/**
 * 获取任务提交的答案列表
 * @param {number} jobId - 任务ID
 * @param {Object} params - 查询参数
 * @param {number} params.page - 页码
 * @param {number} params.size - 每页条数
 * @param {string} params.status - 状态筛选
 * @param {string} params.sort - 排序字段
 * @param {string} params.order - 排序方式
 * @returns {Promise} - 返回答案列表
 */
export const fetchJobAnswers = async (jobId, params = {}) => {
  try {
    const response = await apiClient.get(`/jobs/${jobId}/submissions`, {
      params: {
        page: params.page || 1,
        size: params.size || 10,
        status: params.status,
        sort: params.sort || 'created_at',
        order: params.order || 'desc'
      }
    });
    return response.data;
  } catch (error) {
    console.error("获取任务答案列表失败:", error);
    throw error;
  }
};

/**
 * 提交答案评分
 * @param {Object} data - 评分数据
 * @param {number} data.submissionId - 提交ID
 * @param {number} data.score - 评分（1-10）
 * @returns {Promise} - 返回评分结果
 */
export const submitAnswerScore = async (data) => {
  try {
    const response = await apiClient.post(`/api/v1/jobs/submissions/${data.submissionId}/score`, {
      score: data.score
    });
    return response.data;
  } catch (error) {
    console.error("提交答案评分失败:", error);
    throw error;
  }
};

export const submitAnswerScores = async (scores) => {
  try {
    const response = await axios.post(`${config.baseURL}/job_answer/scores`, {
      scores,
    });
    return response.data;
  } catch (error) {
    console.error("Error submitting answer scores:", error);
    throw error;
  }
};

export const PostRequest = (endpoint, data) => {
  return apiClient
    .post(`${endpoint}`, data)
    .then((response) => response.data)
    .catch((error) => {
      console.error("There was an error with the POST request!", error);
      throw error;
    });
};

// 报名
export const joinJob = async (jobId) => {
  try {
    const response = await apiClient.post(`/jobs/${jobId}/join`);
    return response.data;
  } catch (error) {
    if (error.response) {
      // 处理后端返回的错误
      const status = error.response.status;
      const message = error.response.data;

      if (status === 400) {
        throw new Error(message || "报名失败：请检查任务状态");
      } else if (status === 500) {
        throw new Error(`报名失败：${message || "服务器错误"}`);
      }
    }
    throw new Error("报名失败：网络错误");
  }
};

// 检查用户是否已报名
export const checkJoinStatus = async (jobId) => {
  try {
    const response = await apiClient.get(`/jobs/${jobId}/check-join-status`);
    return response.data;
  } catch (error) {
    if (error.response && error.response.status === 404) {
      return false; // 未报名
    }
    throw error;
  }
};

// 评论相关的API
export const getComments = (activityId, page = 1, size = 10) => {
  return apiClient
    .get(`/comments`, {
      params: {
        activity_id: activityId,
        page: page,
        size: size,
      },
    })
    .then((response) => response.data)
    .catch((error) => {
      console.error("获取评论列表失败:", error);
      throw error;
    });
};

export const createComment = (data) => {
  return apiClient
    .post("/comments", data)
    .then((response) => response.data)
    .catch((error) => {
      console.error("发表评论失败:", error);
      throw error;
    });
};

// 添加回复评论的 API
export const createReply = (data) => {
  return apiClient
    .post("/comments/reply", data)
    .then((response) => response.data)
    .catch((error) => {
      console.error("回复评论失败:", error);
      throw error;
    });
};

// 添加评论点赞的 API
export const toggleCommentLike = (commentId) => {
  return apiClient
    .post(`/comments/${commentId}/like`)
    .then((response) => response.data)
    .catch((error) => {
      console.error("评论点赞操作失败:", error);
      throw error;
    });
};

// 获取群聊消息历史
export const fetchGroupChatMessages = (groupId, messageType) => {
  let url = `/group-chat/${groupId}/messages`;
  if (messageType !== undefined) {
    url += `?messageType=${messageType}`;
  }
  return apiClient
    .get(url)
    .then((response) => response.data)
    .catch((error) => {
      console.error("获取群聊消息失败:", error);
      throw error;
    });
};

// 发送群聊消息
/**
 * 发送群聊消息
 * @param {number} groupId - 群组ID
 * @param {string} content - 消息内容
 * @param {boolean} isAtQwen - 是否@AI助手，true表示需要AI回复
 * @param {number} modelType - AI模型类型：1-千问（默认），2-Deepseek R1，3-Deepseek V3，4-豆包
 * @returns {Promise} - 返回发送结果
 */
export const sendGroupChatMessage = (groupId, content, isAtQwen = false, modelType = 1) => {
  return apiClient
    .post(`/group-chat/${groupId}/send`, {
      content,
      isAtQwen,
      modelType,
    })
    .then((response) => response.data)
    .catch((error) => {
      console.error("发送消息失败:", error);
      throw error;
    });
};

// 获取任务对应的群组ID
export const fetchJobGroupId = (jobId) => {
  return apiClient
    .get(`/group-chat/job/${jobId}/group`)
    .then((response) => response.data)
    .catch((error) => {
      if (error.response && error.response.status === 400) {
        throw new Error("未找到相关群组");
      }
      console.error("获取群组ID失败:", error);
      throw error;
    });
};

// 获取群组名称
export const fetchGroupName = (groupId) => {
  return apiClient
    .get(`/jobs/group/${groupId}/name`)
    .then((response) => response.data)
    .catch((error) => {
      console.error("获取群组名称失败:", error);
      throw error;
    });
};

// 获取群组成员信息
export const fetchGroupMembers = (groupId) => {
  return apiClient
    .get(`/jobs/group/${groupId}/members`)
    .then((response) => {
      if (response.data.code === 200) {
        return response.data.data;
      } else {
        throw new Error(response.data.message || "获取群组成员信息失败");
      }
    })
    .catch((error) => {
      console.error("获取群组成员信息失败:", error);
      throw error;
    });
};

// 删除活动
export const deleteActivity = async (id) => {
  try {
    const response = await apiClient.delete(`/activities/${id}`);
    return response.data;
  } catch (error) {
    console.error("删除活动失败:", error);
    throw error;
  }
};

// 删除任务
export const deleteJob = async (id) => {
  console.log('开始调用deleteJob函数，任务ID:', id);
  try {
    console.log('正在发送删除任务请求...');
    const response = await apiClient.delete(`/jobs/${id}`);
    console.log('删除任务成功，响应数据:', response.data);
    return response.data;
  } catch (error) {
    console.error('删除任务失败:', error);
    if (error.response) {
      console.error('错误响应状态码:', error.response.status);
      console.error('错误响应数据:', error.response.data);
    }
    throw error;
  }
};

// 通知相关的API
export const getNotifications = (page = 1, size = 10) => {
  return apiClient
    .get(`/notifications`, {
      params: {
        page,
        size,
      },
    })
    .then((response) => response.data)
    .catch((error) => {
      console.error("获取通知列表失败:", error);
      throw error;
    });
};

export const getNotificationsByType = (type, page = 1, size = 10) => {
  return apiClient
    .get(`/notifications/type/${type}`, {
      params: {
        page,
        size,
      },
    })
    .then((response) => response.data)
    .catch((error) => {
      console.error(`获取${type}类型通知失败:`, error);
      throw error;
    });
};

export const getUnreadNotifications = (page = 1, size = 10) => {
  return apiClient
    .get(`/notifications/unread`, {
      params: {
        page,
        size,
      },
    })
    .then((response) => response.data)
    .catch((error) => {
      console.error("获取未读通知失败:", error);
      throw error;
    });
};

export const getUnreadNotificationsCount = () => {
  return apiClient
    .get(`/notifications/unread-count`)
    .then((response) => response.data)
    .catch((error) => {
      console.error("获取未读通知数量失败:", error);
      throw error;
    });
};

export const markNotificationAsRead = (notificationId) => {
  return apiClient
    .put(`/notifications/${notificationId}/read`)
    .then((response) => response.data)
    .catch((error) => {
      console.error("标记通知为已读失败:", error);
      throw error;
    });
};

export const markAllNotificationsAsRead = () => {
  return apiClient
    .put(`/notifications/read-all`)
    .then((response) => response.data)
    .catch((error) => {
      console.error("标记所有通知为已读失败:", error);
      throw error;
    });
};

// 根据评论ID获取活动ID的API
export const getActivityIdByCommentId = (commentId) => {
  return apiClient
    .get(`/comments/${commentId}/activity`)
    .then((response) => response.data)
    .catch((error) => {
      console.error("获取评论对应的活动ID失败:", error);
      throw error;
    });
};

// 活动点赞相关的API
export const toggleActivityLike = (activityId) => {
  console.log("调用toggleActivityLike API，活动ID:", activityId);

  return apiClient
    .post(`/activities/like`, { activityId })
    .then((response) => {
      console.log("点赞API响应数据:", response.data);

      // 检查返回的数据结构
      const data = response.data;

      // 如果数据中没有liked字段，记录警告
      if (data && data.liked === undefined) {
        console.warn("点赞API返回数据中没有liked字段");
      }

      // 如果数据中没有点赞数量字段，记录警告
      if (
        data &&
        data.count === undefined &&
        data.likesCount === undefined &&
        data.likeCount === undefined
      ) {
        console.warn("点赞API返回数据中没有点赞数量字段");
      }

      return data;
    })
    .catch((error) => {
      console.error(`点赞操作失败:`, error);
      if (error.response) {
        console.error("错误响应:", error.response.status, error.response.data);
      }
      throw error;
    });
};

// 删除原有的点赞相关API
export const likeActivity = (activityId) => {
  console.warn("likeActivity 方法已过时，请使用新的 toggleActivityLike 方法");
  return toggleActivityLike(activityId);
};

export const unlikeActivity = (activityId) => {
  console.warn("unlikeActivity 方法已过时，请使用新的 toggleActivityLike 方法");
  return toggleActivityLike(activityId);
};

export const getActivityLikeStatus = (activityId) => {
  console.warn(
    "getActivityLikeStatus 方法已过时，使用 fetchActivityDetail 获取点赞状态"
  );
  return Promise.resolve({ isLiked: false });
};

export const getActivityLikeCount = (activityId) => {
  console.warn(
    "getActivityLikeCount 方法已过时，使用 fetchActivityDetail 获取点赞数量"
  );
  return Promise.resolve({ count: 0 });
};

// 根据用户ID查询用户信息
export const queryUserById = (userId) => {
  return apiClient
    .get("/user/query", {
      params: {
        id: userId,
      },
    })
    .then((response) => response.data)
    .catch((error) => {
      console.error("获取用户信息失败:", error);
      throw error;
    });
};

// 终止任务
export const terminateJob = async (jobId) => {
  try {
    const response = await apiClient.post(`/job/${jobId}/terminate`);
    return response.data;
  } catch (error) {
    console.error("终止任务失败:", error);
    throw error;
  }
};

// 获取任务数据和报名状态
export const fetchJobDataWithStatus = async (jobId) => {
  try {
    const [jobData, joinStatus] = await Promise.all([
      fetchJobById(jobId),
      checkJoinStatus(jobId)
    ]);
    return { jobData, joinStatus };
  } catch (error) {
    console.error("获取任务数据失败:", error);
    throw error;
  }
};

// 群组文件上传
export const uploadGroupFile = (formData) => {
  return apiClient
    .post('/jobs/groupfileupload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    .then(response => response.data)
    .catch(error => {
      console.error('文件上传失败:', error);
      throw error;
    });
};

// 群组文件下载
export const downloadGroupFile = async (groupId, fileId) => {
  try {
    const response = await apiClient.get(`/jobs/groupfiledo/${groupId}/${fileId}`, {
      responseType: 'blob'
    });
    if (response.data instanceof Blob) {
      return response.data;
    } else {
      // 如果返回的不是Blob，尝试从fileUrl获取文件内容
      const fileData = response.data;
      if (fileData && fileData.data && fileData.data.fileUrl) {
        const fileUrl = fileData.data.fileUrl.trim();
        const fileResponse = await apiClient.get(fileUrl, {
          responseType: 'blob'
        });
        return fileResponse.data;
      }
      throw new Error('无效的文件数据');
    }
  } catch (error) {
    console.error('文件下载失败:', error);
    throw error;
  }
};

// 群组文件删除
export const deleteGroupFile = (groupId, fileId) => {
  return apiClient
    .delete(`/jobs/groupfiledo/${groupId}/${fileId}`)
    .then(response => response.data)
    .catch(error => {
      console.error('文件删除失败:', error);
      throw error;
    });
};

// 获取群组文件列表
export const fetchGroupFiles = (groupId) => {
  console.log(`开始获取群组(${groupId})的文件列表`);
  console.log('请求URL:', `/jobs/groupfilelist/${groupId}`);
  return apiClient
    .get(`/jobs/groupfilelist/${groupId}`)
    .then(response => {
      console.log('API响应成功，完整响应对象:', response);
      console.log('响应状态码:', response.status);
      console.log('响应数据:', response.data);
      if (response.data && response.data.code === 200) {
        const files = response.data.data.records || [];
        console.log(`找到 ${files.length} 个文件，groupId匹配检查:`, 
          files.map(f => ({id: f.id, groupId: f.groupId})));
      }
      return response.data;
    })
    .catch(error => {
      console.error('获取群组文件列表失败:', error);
      if (error.response) {
        console.error('错误响应:', error.response.data);
        console.error('状态码:', error.response.status);
      }
      throw error;
    });
};

// 提交相关的API
export const getSubmission = (jobId, groupId) => {
  return apiClient.get(`/jobs/${jobId}/groups/${groupId}/submission`)
    .then(response => response.data)
    .catch(error => {
      console.error('获取提交内容失败:', error);
      throw error;
    });
};

// 获取用户提交内容
export const getUserSubmission = (jobId, groupId) => {
  return apiClient.get(`/api/user-job-submissions/${jobId}/groups/${groupId}/user`)
    .then(response => response.data)
    .catch(error => {
      console.error('获取用户提交内容失败:', error);
      throw error;
    });
};

// 提交用户内容
export const submitUserContent = (jobId, groupId, content, status = 'PENDING') => {
  return apiClient.post(`/api/user-job-submissions/${jobId}/groups/${groupId}`, { 
    content,
    status
  })
    .then(response => response.data)
    .catch(error => {
      console.error('提交用户内容失败:', error);
      throw error;
    });
};

export const submitContent = (jobId, groupId, content) => {
  return apiClient.post(`/jobs/${jobId}/groups/${groupId}/submission`, { content })
    .then(response => response.data)
    .catch(error => {
      console.error('提交内容失败:', error);
      throw error;
    });
};

export const deleteSubmission = (jobId, groupId) => {
  return apiClient.delete(`/jobs/${jobId}/groups/${groupId}/submission`)
    .then(response => response.data)
    .catch(error => {
      console.error('删除提交失败:', error);
      throw error;
    });
};

/**
 * 获取单个答案详情
 * @param {number} submissionId - 提交ID
 * @returns {Promise} - 返回答案详情
 */
export const fetchSubmissionDetail = async (submissionId) => {
  try {
    const response = await apiClient.get(`/jobs/submissions/${submissionId}`);
    return response.data;
  } catch (error) {
    console.error("获取答案详情失败:", error);
    throw error;
  }
};

// 评分标准相关的API
/**
 * 获取任务的评分标准
 * @param {number} jobId - 任务ID
 * @returns {Promise} - 返回评分标准列表
 */
export const getScoringCriteria = async (jobId) => {
  try {
    const response = await apiClient.get(`/jobs/${jobId}/scoring-criteria`);
    return response.data;
  } catch (error) {
    console.error("获取评分标准失败:", error);
    throw error;
  }
};

/**
 * 创建评分标准
 * @param {Object} data - 评分标准数据
 * @param {number} data.jobId - 任务ID
 * @param {Array} data.criteria - 评分标准列表
 * @returns {Promise} - 返回创建结果
 */
export const createScoringCriteria = async (data) => {
  try {
    const response = await apiClient.post(`/jobs/${data.jobId}/scoring-criteria`, {
      criteria: data.criteria
    });
    return response.data;
  } catch (error) {
    console.error("创建评分标准失败:", error);
    throw error;
  }
};

/**
 * 更新评分标准
 * @param {number} jobId - 任务ID
 * @param {number} criteriaId - 评分标准ID
 * @param {Object} data - 更新的评分标准数据
 * @returns {Promise} - 返回更新结果
 */
export const updateScoringCriteria = async (jobId, criteriaId, data) => {
  try {
    const response = await apiClient.put(`/jobs/${jobId}/scoring-criteria/${criteriaId}`, data);
    return response.data;
  } catch (error) {
    console.error("更新评分标准失败:", error);
    throw error;
  }
};

/**
 * 删除评分标准
 * @param {number} jobId - 任务ID
 * @param {number} criteriaId - 评分标准ID
 * @returns {Promise} - 返回删除结果
 */
export const deleteScoringCriteria = async (jobId, criteriaId) => {
  try {
    const response = await apiClient.delete(`/jobs/${jobId}/scoring-criteria/${criteriaId}`);
    return response.data;
  } catch (error) {
    console.error("删除评分标准失败:", error);
    throw error;
  }
};

// 评分操作相关的API
/**
 * 获取待评分的提交列表
 * @param {number} jobId - 任务ID
 * @param {Object} params - 查询参数
 * @param {number} params.page - 页码
 * @param {number} params.size - 每页条数
 * @param {string} params.status - 状态筛选
 * @param {string} params.sort - 排序字段
 * @param {string} params.order - 排序方式
 * @returns {Promise} - 返回提交列表
 */
export const getPendingSubmissions = async (jobId, params = {}) => {
  try {
    const response = await apiClient.get(`/jobs/${jobId}/submissions`, {
      params: {
        page: params.page || 1,
        size: params.size || 10,
        status: params.status || 'PENDING',
        sort: params.sort || 'created_at',
        order: params.order || 'desc'
      }
    });
    return response.data;
  } catch (error) {
    console.error("获取待评分列表失败:", error);
    throw error;
  }
};

/**
 * 提交评分
 * @param {number} submissionId - 提交ID
 * @param {Object} data - 评分数据
 * @param {Array} data.scores - 评分列表
 * @returns {Promise} - 返回评分结果
 */
export const submitScores = async (submissionId, data) => {
  try {
    const response = await apiClient.post(`/jobs/submissions/${submissionId}/scores`, data);
    return response.data;
  } catch (error) {
    console.error("提交评分失败:", error);
    throw error;
  }
};

/**
 * 更新评分
 * @param {number} submissionId - 提交ID
 * @param {Object} data - 更新的评分数据
 * @returns {Promise} - 返回更新结果
 */
export const updateScores = async (submissionId, data) => {
  try {
    const response = await apiClient.put(`/jobs/submissions/${submissionId}/scores`, data);
    return response.data;
  } catch (error) {
    console.error("更新评分失败:", error);
    throw error;
  }
};

/**
 * 获取评分历史
 * @param {number} submissionId - 提交ID
 * @returns {Promise} - 返回评分历史
 */
export const getScoreHistory = async (submissionId) => {
  try {
    const response = await apiClient.get(`/jobs/submissions/${submissionId}/scores/history`);
    return response.data;
  } catch (error) {
    console.error("获取评分历史失败:", error);
    throw error;
  }
};

/**
 * 获取评分统计
 * @param {number} jobId - 任务ID
 * @returns {Promise} - 返回评分统计数据
 */
export const getScoreStatistics = async (jobId) => {
  try {
    const response = await apiClient.get(`/jobs/${jobId}/submissions/scores/statistics`);
    return response.data;
  } catch (error) {
    console.error("获取评分统计失败:", error);
    throw error;
  }
};

/**
 * 获取提交的评分标准
 * @param {number} submissionId - 提交ID
 * @returns {Promise} - 返回评分标准列表
 */
export const getSubmissionScoringCriteria = async (submissionId) => {
  try {
    const response = await apiClient.get(`/api/submissions/${submissionId}/scoring-criteria`);
    return response.data;
  } catch (error) {
    console.error("获取评分标准失败:", error);
    throw error;
  }
};

/**
 * 提交评分
 * @param {number} submissionId - 提交ID
 * @param {Array} scores - 评分数据数组
 * @returns {Promise} - 返回评分结果
 */
export const submitSubmissionScores = async (submissionId, scores) => {
  try {
    const response = await apiClient.post(`/api/submissions/${submissionId}/scores`, {
      scores: scores
    });
    return response.data;
  } catch (error) {
    console.error("提交评分失败:", error);
    throw error;
  }
};

/**
 * 获取提交的评分信息
 * @param {number} submissionId - 提交ID
 * @returns {Promise} - 返回评分信息
 */
export const getSubmissionScores = async (submissionId) => {
  try {
    const response = await apiClient.get(`/api/submissions/${submissionId}/scores`);
    return response.data;
  } catch (error) {
    console.error("获取评分信息失败:", error);
    throw error;
  }
};

// 提交评分
export const submitScore = ({ jobId, submissionId, scores }) => {
  return apiClient
    .post(`/api/submissions/jobs/${jobId}/submissions/${submissionId}/scores`, { scores })
    .then(response => response.data)
    .catch(error => {
      console.error('提交评分失败:', error);
      throw error;
    });
};

export default apiClient;

